import base64
import datetime
import logging
from flask import Blueprint, render_template, request, jsonify
from bilibili_api import search, sync, video
from exts import db
from models import MonitoringTask, MonitoredVideo, Comment, Alert, ReportedAccount
import requests
import asyncio
from script.spider_common_method import save_video, filter_string, get_all_comment, update_comment, \
    delete_video_comments, \
    re_crawling_video_comments
from utils.CredentialUtil import CredentialConfig
from utils.DataVisualization import VisualizationTool

comment_bp = Blueprint("comment", __name__, url_prefix="/comment")


@comment_bp.route('/get_violence_comments/<bvid>')
def get_violence_comments(bvid):
    comments = []
    is_violence_comments = Comment.query.filter_by(bvid=bvid, is_violence=True, is_banned=False).all()
    for c in is_violence_comments:
        c = c.__dict__
        del c['_sa_instance_state']
        comments.append(c)
    return jsonify(comments), 200


@comment_bp.route('/get_sarcasm_comments/<bvid>')
def get_sarcasm_comments(bvid):
    comments = []
    is_violence_comments = Comment.query.filter_by(bvid=bvid, is_sarcasm=True, is_banned=False).all()
    for c in is_violence_comments:
        c = c.__dict__
        del c['_sa_instance_state']
        comments.append(c)
    return jsonify(comments), 200


@comment_bp.route('/get_did_violence_comments/<bvid>')
def get_did_violence_comments(bvid):
    comments = []
    is_violence_comments = Comment.query.filter_by(bvid=bvid, is_did_violence=True, is_banned=False).all()
    for c in is_violence_comments:
        c = c.__dict__
        del c['_sa_instance_state']
        comments.append(c)
    return jsonify(comments), 200


@comment_bp.route('/get_banned_comments/<bvid>')
def get_banned_comments(bvid):
    comments = []
    is_violence_comments = Comment.query.filter_by(bvid=bvid, is_banned=True).all()
    for c in is_violence_comments:
        c = c.__dict__
        del c['_sa_instance_state']
        comments.append(c)
    return jsonify(comments), 200


@comment_bp.route('/violence_gender_pie/<bvid>')
def get_video_violence_comment_pie(bvid):
    comments = Comment.query.filter_by(bvid=bvid, is_violence=1).all()
    violence_pie = VisualizationTool.comments_gender_pies(comments)
    return violence_pie.dump_options_with_quotes()


@comment_bp.route('/all_gender_pie/<bvid>')
def get_video_all_comment_pie(bvid):
    comments = Comment.query.filter_by(bvid=bvid).all()
    all_pie = VisualizationTool.comments_gender_pies(comments)
    return all_pie.dump_options_with_quotes()


@comment_bp.route('/ban/<bvid>/<comment_id>')
def ban_comment(bvid, comment_id):
    try:
        comment = Comment.query.filter_by(id=comment_id).first()
        comment.is_banned = True
        report_account = ReportedAccount(bvid=bvid, rpid=comment.rpid,
                                         comment_content=comment.content,
                                         account_id=comment.account_id,
                                         account_name=comment.account_name,
                                         account_sex=comment.account_sex,
                                         account_level=comment.account_level,
                                         comment_publish_time=comment.publish_time,
                                         is_violence=comment.is_violence,
                                         is_sarcasm=comment.is_sarcasm,
                                         is_did_violence=comment.is_did_violence,
                                         banned_time=datetime.datetime.now())
        db.session.add(report_account)
        db.session.commit()
        return jsonify({'success': 'success'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': 'Failed to ban'}), 500


@comment_bp.route('/ban_all/<bvid>/<comment_type>')
def ban_all_comment(bvid, comment_type):
    try:
        if comment_type == 'get_violence_comments':
            comments = Comment.query.filter_by(bvid=bvid, is_violence=True, is_banned=False).all()
        elif comment_type == 'get_sarcasm_comments':
            comments = Comment.query.filter_by(bvid=bvid, is_sarcasm=True, is_banned=False).all()
        elif comment_type == 'get_did_violence_comments':
            comments = Comment.query.filter_by(bvid=bvid, is_did_violence=True, is_banned=False).all()
        for comment in comments:
            comment.is_banned = True
            report_account = ReportedAccount(bvid=bvid, rpid=comment.rpid,
                                             comment_content=comment.content,
                                             account_id=comment.account_id,
                                             account_name=comment.account_name,
                                             account_sex=comment.account_sex,
                                             account_level=comment.account_level,
                                             comment_publish_time=comment.publish_time,
                                             is_violence=comment.is_violence,
                                             is_sarcasm=comment.is_sarcasm,
                                             is_did_violence=comment.is_did_violence,
                                             banned_time=datetime.datetime.now())
            db.session.add(report_account)
        db.session.commit()
        return jsonify({'success': 'success'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': 'Failed to ban'}), 500


@comment_bp.route('/unban/<comment_rpid>')
def unban_comment(comment_rpid):
    try:
        report_account = ReportedAccount.query.filter_by(rpid=comment_rpid).first()
        comment = Comment.query.filter_by(rpid=comment_rpid).first()
        comment.is_banned = False
        db.session.delete(report_account)
        db.session.commit()
        return jsonify({'success': 'success'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': 'Failed to ban'}), 500


@comment_bp.route('/unban_all/<bvid>')
def unban_all_comment(bvid):
    try:
        report_accounts = ReportedAccount.query.filter_by(bvid=bvid).all()
        rpid = []
        for r in report_accounts:
            rpid.append(r.rpid)
        comments = Comment.query.filter(rpid in rpid).all()
        for c in comments:
            c.is_banned = False
        db.session.commit()
        db.session.delete(report_accounts)
        db.session.commit()
        return jsonify({'success': 'success'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': 'Failed to ban'}), 500
